﻿using Engine;
using Engine.Graphics;
using GameEntitySystem;
using System;
using System.Collections.Generic;
using Game;
using Engine.Media;
using System.IO;

namespace JackODummy
{
	public static class JackOUtility
	{
		public static int BlockIndex(this Type type)
		{
			return BlocksManager.GetBlockIndex(type);
		}
		static RenderTarget2D m_innerClothedTexture;
		static readonly PrimitivesRenderer2D m_primitivesRenderer = new();

		static readonly Dictionary<string, int> clothesToDraw = new()
		{
			{ "Textures/Clothing/OldHat", 0 },
			{ "Textures/Clothing/OldTankTop", 0 },
			{ "Textures/Clothing/OldShirt", 9 }
		};
		public static void DrawClothedTexture()
		{
			m_innerClothedTexture ??= new RenderTarget2D(64, 64, 1, ColorFormat.Rgba8888, DepthFormat.None);
			Rectangle scissorRectangle = Display.ScissorRectangle;
			RenderTarget2D renderTarget = Display.RenderTarget;
			try
			{
				Display.RenderTarget = m_innerClothedTexture;
				Display.Clear(new Vector4(Color.Transparent));
				int num = 0;
				TexturedBatch2D texturedBatch2D;
				foreach (var item in clothesToDraw)
				{
					texturedBatch2D = m_primitivesRenderer.TexturedBatch(ContentManager.Get<Texture2D>(item.Key), useAlphaTest: false, num++, DepthStencilState.None, null, BlendState.NonPremultiplied, SamplerState.PointClamp);
					Color fabricColor = SubsystemPalette.GetFabricColor(SubsystemTerrain, item.Value);
					texturedBatch2D.QueueQuad(new Vector2(0f, 0f), new Vector2(m_innerClothedTexture.Width, m_innerClothedTexture.Height), 0f, Vector2.Zero, Vector2.One, fabricColor);
				}
				m_primitivesRenderer.Flush();
			}
			finally
			{
				Display.RenderTarget = renderTarget;
				Display.ScissorRectangle = scissorRectangle;
			}
			string screenshotDir = ScreenCaptureManager.ScreenshotDir;
			if (!Storage.DirectoryExists(screenshotDir))
				Storage.CreateDirectory(screenshotDir);
			using Stream stream = Storage.OpenFile(Storage.CombinePaths(screenshotDir, "Cloth.png"), OpenFileMode.CreateOrOpen);
			Image.Save(m_innerClothedTexture.GetData(new Rectangle(0, 0, m_innerClothedTexture.Width, m_innerClothedTexture.Height)), stream, ImageFileFormat.Png, saveAlpha: false);
		}

		public static SubsystemTerrain SubsystemTerrain
		{
			get; set;
		}
		public static SubsystemGameInfo SubsystemGameInfo
		{
			get; set;
		}
		public static SubsystemParticles SubsystemParticles
		{
			get; set;
		}
		public static SubsystemTime SubsystemTime
		{
			get; set;
		}
		public static void LoadSubsystems(Project project)
		{
			SubsystemTerrain = project.FindSubsystem<SubsystemTerrain>(throwOnError: true);
			SubsystemGameInfo = project.FindSubsystem<SubsystemGameInfo>(throwOnError: true);
			SubsystemParticles = project.FindSubsystem<SubsystemParticles>(throwOnError: true);
			SubsystemTime = project.FindSubsystem<SubsystemTime>(throwOnError: true);
		}

	}
}
